<?php
/**
 * 商品栏目管理
 *
 *
 *
 **你正在使用的程序由BESONIT提供*/

defined('BYshopJL') or exit('Access Invalid!');
class goodsControl extends SystemControl{
    const EXPORT_SIZE = 5000;
    public function __construct() {
        parent::__construct ();
        Language::read('goods');
    }

    /**
     * 商品设置
     */
    public function goods_setOp() {
		$model_setting = Model('setting');
		if (chksubmit()){
			$update_array = array();
			$update_array['goods_verify'] = $_POST['goods_verify'];
			$result = $model_setting->updateSetting($update_array);
			if ($result === true){
				$this->log(L('nc_edit,nc_goods_set'),1);
				showMessage(L('nc_common_save_succ'));
			}else {
				$this->log(L('nc_edit,nc_goods_set'),0);
				showMessage(L('nc_common_save_fail'));
			}
		}
		$list_setting = $model_setting->getListSetting();
		Tpl::output('list_setting',$list_setting);
        Tpl::showpage('goods.setting');
    }
    /**
     * 商品管理
     */
    public function goodsOp() {
        $model_goods = Model ( 'goods' );
        /**
         * 处理商品分类
         */
        $choose_gcid = ($t = intval($_REQUEST['choose_gcid']))>0?$t:0;
        $gccache_arr = Model('goods_class')->getGoodsclassCache($choose_gcid,3);
	    Tpl::output('gc_json',json_encode($gccache_arr['showclass']));
		Tpl::output('gc_choose_json',json_encode($gccache_arr['choose_gcid']));

        /**
         * 查询条件
         */
        $where = array();
        if ($_GET['search_goods_name'] != '') {
            $where['goods_name'] = array('like', '%' . trim($_GET['search_goods_name']) . '%');
        }
        if (intval($_GET['search_commonid']) > 0) {
            $where['goods_commonid'] = intval($_GET['search_commonid']);
        }
        if ($_GET['search_store_name'] != '') {
            $where['store_name'] = array('like', '%' . trim($_GET['search_store_name']) . '%');
        }
        if (intval($_GET['b_id']) > 0) {
            $where['brand_id'] = intval($_GET['b_id']);
        }
        if ($choose_gcid > 0){
		    $where['gc_id_'.($gccache_arr['showclass'][$choose_gcid]['depth'])] = $choose_gcid;
		}
        if (in_array($_GET['search_state'], array('0','1','10'))) {
            $where['goods_state'] = $_GET['search_state'];
        }
        if (in_array($_GET['search_verify'], array('0','1','10'))) {
            $where['goods_verify'] = $_GET['search_verify'];
        }

        switch ($_GET['type']) {
            // 禁售
            case 'lockup':
                $goods_list = $model_goods->getGoodsCommonLockUpList($where);
                break;
            // 等待审核
            case 'waitverify':
                $goods_list = $model_goods->getGoodsCommonWaitVerifyList($where, '*', 10, 'goods_verify desc, goods_commonid desc');
                break;
            // 全部商品
            default:
                $goods_list = $model_goods->getGoodsCommonList($where);
                break;
        }

        Tpl::output('goods_list', $goods_list);
        Tpl::output('page', $model_goods->showpage(2));

        $storage_array = $model_goods->calculateStorage($goods_list);
        Tpl::output('storage_array', $storage_array);

        // 品牌
        $brand_list = Model('brand')->getBrandPassedList(array());

        Tpl::output('search', $_GET);
        Tpl::output('brand_list', $brand_list);

        Tpl::output('state', array('1' => '出售中', '0' => '仓库中', '10' => '违规下架'));

        Tpl::output('verify', array('1' => '通过', '0' => '未通过', '10' => '等待审核'));

        Tpl::output('ownShopIds', array_fill_keys(Model('store')->getOwnShopIds(), true));

        switch ($_GET['type']) {
            // 禁售
            case 'lockup':
                Tpl::showpage('goods.close');
                break;
            // 等待审核
            case 'waitverify':
                Tpl::showpage('goods.verify');
                break;
            // 全部商品
            default:
                Tpl::showpage('goods.index');
                break;
        }
    }

    /**
     * 违规下架
     */
    public function goods_lockupOp() {
        if (chksubmit()) {
            $commonids = $_POST['commonids'];
            $commonid_array = explode(',', $commonids);
            foreach ($commonid_array as $value) {
                if (!is_numeric($value)) {
                    showDialog(L('nc_common_op_fail'), 'reload');
                }
            }
            $update = array();
            $update['goods_stateremark'] = trim($_POST['close_reason']);

            $where = array();
            $where['goods_commonid'] = array('in', $commonid_array);

            Model('goods')->editProducesLockUp($update, $where);
            showDialog(L('nc_common_op_succ'), 'reload', 'succ');
        }
        Tpl::output('commonids', $_GET['id']);
        Tpl::showpage('goods.close_remark', 'null_layout');
    }

    /**
     * 删除商品
     */
    public function goods_delOp() {
        $common_id = intval($_GET['goods_id']);
        if ($common_id <= 0) {
            showDialog(L('nc_common_op_fail'), 'reload');
        }
        Model('goods')->delGoodsAll(array('goods_commonid' => $common_id));
        showDialog(L('nc_common_op_succ'), 'reload', 'succ');
    }

    /**
     * 审核商品
     */
    public function goods_verifyOp(){
        if (chksubmit()) {
            $commonids = $_POST['commonids'];
            $commonid_array = explode(',', $commonids);
            foreach ($commonid_array as $value) {
                if (!is_numeric($value)) {
                    showDialog(L('nc_common_op_fail'), 'reload');
                }
            }
            $update2 = array();
            $update2['goods_verify'] = intval($_POST['verify_state']);

            $update1 = array();
            $update1['goods_verifyremark'] = trim($_POST['verify_reason']);
            $update1 = array_merge($update1, $update2);
            $where = array();
            $where['goods_commonid'] = array('in', $commonid_array);

            $model_goods = Model('goods');
            if (intval($_POST['verify_state']) == 0) {
                $model_goods->editProducesVerifyFail($where, $update1, $update2);
            } else {
                $model_goods->editProduces($where, $update1, $update2);
            }
            showDialog(L('nc_common_op_succ'), 'reload', 'succ');
        }
        Tpl::output('commonids', $_GET['id']);
        Tpl::showpage('goods.verify_remark', 'null_layout');
    }

    /**
     * ajax获取商品列表
     */
    public function get_goods_list_ajaxOp() {
        $commonid = $_GET['commonid'];
        if ($commonid <= 0) {
            echo 'false';exit();
        }
        $model_goods = Model('goods');
        $goodscommon_list = $model_goods->getGoodeCommonInfoByID($commonid, 'spec_name');
        if (empty($goodscommon_list)) {
            echo 'false';exit();
        }
        $goods_list = $model_goods->getGoodsList(array('goods_commonid' => $commonid), 'goods_id,goods_spec,store_id,goods_price,goods_serial,goods_storage,goods_image');
        if (empty($goods_list)) {
            echo 'false';exit();
        }

        $spec_name = array_values((array)unserialize($goodscommon_list['spec_name']));
        foreach ($goods_list as $key => $val) {
            $goods_spec = array_values((array)unserialize($val['goods_spec']));
            $spec_array = array();
            foreach ($goods_spec as $k => $v) {
                $spec_array[] = '<div class="goods_spec">' . $spec_name[$k] . L('nc_colon') . '<em title="' . $v . '">' . $v .'</em>' . '</div>';
            }
            $goods_list[$key]['goods_image'] = thumb($val, '60');
            $goods_list[$key]['goods_spec'] = implode('', $spec_array);
            $goods_list[$key]['url'] = urlShop('goods', 'index', array('goods_id' => $val['goods_id']));
        }

        /**
         * 转码
         */
        if (strtoupper(CHARSET) == 'GBK') {
            Language::getUTF8($goods_list);
        }
        echo json_encode($goods_list);
    }

    /**
     * sellOp
     * 商品销售记录明细
     */
    public function sellOp(){

        $add_time_to = date("Y-m-d");
        $time_from = array();
        $time_from['7'] = strtotime($add_time_to) - 60 * 60 * 24 * 7;
        if (empty($_GET['add_time_from']) || $_GET['add_time_from'] > $add_time_to) {//默认显示7天内数据
            $_GET['add_time_from'] = date("Y-m-d", $time_from['7']);
        }
        if (empty($_GET['add_time_to'])) {
            $_GET['add_time_to'] = $add_time_to;
        }

        $f_key = trim($_GET['f_key']);
        $condition = array();
        if (!empty($f_key)) {
            $condition['order_goods.goods_name|order_goods.goods_id'] = array(array('like', '%' . $f_key . '%'));
        }
        $start = intval(strtotime(trim($_GET['add_time_from']))) ;
        $end = intval(strtotime(trim($_GET['add_time_to'])))+86400;
        $condition['order.add_time'] = array('between', "$start , $end" );
        $result = Model('order')->getOrderAndOrderGoodsList($condition,'order_goods.*,order.add_time,order.order_sn',10);
        Tpl::output('show_page', Model('order')->showpage());
        Tpl::output('sell_list', $result);
        Tpl::showpage('goods.sell');
    }

    /**
     * sellRecordOp
     * 商品销售记录统计
     */
    public function sellRecordOp(){

        $add_time_to = date("Y-m-d");
        $time_from = array();
        $time_from['7'] = strtotime($add_time_to) - 60 * 60 * 24 * 7;
        if (empty($_GET['add_time_from']) || $_GET['add_time_from'] > $add_time_to) {//默认显示7天内数据
            $_GET['add_time_from'] = date("Y-m-d", $time_from['7']);
        }
        if (empty($_GET['add_time_to'])) {
            $_GET['add_time_to'] = $add_time_to;
        }

        global $config;
        $f_key = trim($_GET['f_key']);
        $curpage = isset($_GET['curpage']) && !empty($_GET['curpage']) ? intval($_GET['curpage']) : 1;
        pagecmd('setEachNum', 10);

        if (!empty($f_key)) {
            $sql_start = "SELECT new_t.*,sum(new_t.goods_num) as all_goods_num,sum(new_t.goods_pay) as all_goods_pay,sum(new_t.brokerage) as all_brokerages FROM ( ";
            $sql= "SELECT order_goods.goods_id,order_goods.goods_name,order_goods.goods_num,(order_goods.goods_num * order_goods.goods_pay_price) as goods_pay,order_goods.brokerage,order.add_time,order.order_sn FROM {$config['tablepre']}order_goods AS `order_goods` INNER JOIN {$config['tablepre']}order AS `order` ON order_goods.order_id=order.order_id WHERE (  (order.add_time BETWEEN ".intval(strtotime(trim($_GET['add_time_from']))) ."  AND ".(intval(strtotime(trim($_GET['add_time_to'])))+86400) ."  ) and (order_goods.`goods_name` like '%{$f_key}%' or order_goods.`goods_id` like '%{$f_key}%') ))";
            $sql.= "AS new_t  GROUP BY new_t.goods_id ORDER BY new_t.`add_time` DESC ";
            $count_sql = "SELECT count(*) FROM ( ".$sql_start.$sql.") as t";
            $list_sql = $sql_start.$sql." LIMIT ".($curpage-1)*10 .",10";
            $totalNum = Model()->query($count_sql);
            $result = Model()->query($list_sql);
            pagecmd('setTotalNum', intval($totalNum[0]['count(*)']));
        }else{
            $sql_start = "SELECT new_t.*,sum(new_t.goods_num) as all_goods_num,sum(new_t.goods_pay) as all_goods_pay,sum(new_t.brokerage) as all_brokerages FROM ( ";
            $sql= "SELECT order_goods.goods_id,order_goods.goods_name,order_goods.goods_num,(order_goods.goods_num * order_goods.goods_pay_price) as goods_pay,order_goods.brokerage,order.add_time,order.order_sn FROM {$config['tablepre']}order_goods AS `order_goods` INNER JOIN {$config['tablepre']}order AS `order` ON order_goods.order_id=order.order_id WHERE (  (order.add_time BETWEEN ".intval(strtotime(trim($_GET['add_time_from']))) ."  AND ".(intval(strtotime(trim($_GET['add_time_to'])))+86400) ."  )) )";
            $sql.= "AS new_t  GROUP BY new_t.goods_id ORDER BY new_t.`add_time` DESC ";
            $count_sql = "SELECT count(*) FROM ( ".$sql_start.$sql.") as t";
            $list_sql = $sql_start.$sql." LIMIT ".($curpage-1)*10 .",10";
            $totalNum = Model()->query($count_sql);
            $result = Model()->query($list_sql);
            //file_put_contents('a.sql',$list_sql.";\r\n",FILE_APPEND);
            pagecmd('setTotalNum', intval($totalNum[0]['count(*)']));
        }
        Tpl::output('show_page', Model()->showpage());
        Tpl::output('sell_list', $result);
        Tpl::showpage('goods.sell_record');
    }


    public function shareOp(){
        $add_time_to = date("Y-m-d");
        $time_from = array();
        $time_from['7'] = strtotime($add_time_to) - 60 * 60 * 24 * 7;
        if (empty($_GET['add_time_from']) || $_GET['add_time_from'] > $add_time_to) {//默认显示7天内数据
            $_GET['add_time_from'] = date("Y-m-d", $time_from['7']);
        }
        if (empty($_GET['add_time_to'])) {
            $_GET['add_time_to'] = $add_time_to;
        }
        global $config;
        $f_key = trim($_GET['f_key']);
        $curpage = isset($_GET['curpage']) && !empty($_GET['curpage']) ? intval($_GET['curpage']) : 1;
        pagecmd('setEachNum', 10);
        $start = intval(strtotime(trim($_GET['add_time_from']))) ;
        $end = intval(strtotime(trim($_GET['add_time_to'])))+86400;
        if (!empty($f_key)) {
            $sql ="SELECT og.*,o.order_state,o.order_sn,o.add_time,m1.member_name AS buyer_name,m2.member_name AS share_name FROM {$config['tablepre']}order_goods AS og INNER JOIN {$config['tablepre']}order AS o ON og.`order_id` = o.`order_id` LEFT JOIN {$config['tablepre']}member AS m1 ON og.buyer_id = m1.member_id LEFT JOIN {$config['tablepre']}member AS m2 ON og.brokerage_account = m2.member_id";
            $sql.=" WHERE (  (o.add_time BETWEEN $start AND $end  ) and (og.`goods_name` like '%{$f_key}%' or og.`goods_id` like '%{$f_key}%') and og.`brokerage_account` >0  )  ORDER BY o.`add_time` DESC";
            $count_sql = "SELECT count(*) FROM ( ".$sql.") as t";
            $list_sql = $sql." LIMIT ".($curpage-1)*10 .",10";
            $totalNum = Model()->query($count_sql);
            $result = Model()->query($list_sql);
            pagecmd('setTotalNum', intval($totalNum[0]['count(*)']));
        }else{
            $sql ="SELECT og.*,o.order_state,o.order_sn,o.add_time,m1.member_name AS buyer_name,m2.member_name AS share_name FROM {$config['tablepre']}order_goods AS og INNER JOIN {$config['tablepre']}order AS o ON og.`order_id` = o.`order_id` LEFT JOIN {$config['tablepre']}member AS m1 ON og.buyer_id = m1.member_id LEFT JOIN {$config['tablepre']}member AS m2 ON og.brokerage_account = m2.member_id WHERE (  (o.add_time BETWEEN $start AND $end  ) and og.`brokerage_account` >0 ) ORDER BY o.`add_time` DESC";
            $count_sql = "SELECT count(*) FROM ( ".$sql.") as t";
            $list_sql = $sql." LIMIT ".($curpage-1)*10 .",10";
            $totalNum = Model()->query($count_sql);
            $result = Model()->query($list_sql);
            pagecmd('setTotalNum', intval($totalNum[0]['count(*)']));
        }
        Tpl::output('show_page', Model()->showpage());
        Tpl::output('share_list', $result);
        Tpl::showpage('goods.share');
    }

    /**
     * shareRecord
     * 分享产品统计
     */
    public function shareRecordOp(){
        $add_time_to = date("Y-m");
        $time_from = array();
        $time_from['7'] = strtotime($add_time_to) - 60 * 60 * 24 * 7;
        if (empty($_GET['add_time_from']) || $_GET['add_time_from'] > $add_time_to) {//默认显示7天内数据
            $_GET['add_time_from'] = date("Y-m", $time_from['7']);
        }
        if (empty($_GET['add_time_to'])) {
            $_GET['add_time_to'] = $add_time_to;
        }
        global $config;
        $f_key = trim($_GET['f_key']);
        $curpage = isset($_GET['curpage']) && !empty($_GET['curpage']) ? intval($_GET['curpage']) : 1;
        pagecmd('setEachNum', 10);
        if (!empty($f_key)) {
            $sql_start = "SELECT g.*,sum(v.`month_view`) as `month_view` FROM ( ";
            $sql= "SELECT `goods_id`,`goods_name`,sum(`goods_pay_price`) as all_goods_price,count(*) as order_count,sum(`brokerage`) as all_brokerage FROM {$config['tablepre']}order_goods WHERE `goods_name` like '%{$f_key}%' GROUP BY `goods_id`) ";
            $sql.= "AS g LEFT JOIN {$config['tablepre']}bs_goods_view AS v ON g.`goods_id` = v.`goods_id` WHERE v.`year_month`>".intval(strtotime(trim($_GET['add_time_from'])));
            $sql.= " AND v.`year_month`<=".intval(strtotime(trim($_GET['add_time_to'])));
            $sql_end= " GROUP BY g.`goods_id`";
            $count_sql = "SELECT count(*) FROM ( ".$sql_start.$sql.$sql_end.") as t";
            $list_sql = $sql_start.$sql.$sql_end." LIMIT ".($curpage-1)*10 .",10";
            $totalNum = Model()->query($count_sql);
            $share_result = Model()->query($list_sql);

            pagecmd('setTotalNum', intval($totalNum[0]['count(*)']));
        }else{
            $sql_start = "SELECT g.*,sum(v.`month_view`) as `month_view` FROM ( ";
            $sql= "SELECT `goods_id`,`goods_name`,sum(`goods_pay_price`) as all_goods_price,count(*) as order_count,sum(`brokerage`) as all_brokerage FROM {$config['tablepre']}order_goods  GROUP BY `goods_id`) ";
            $sql.= "AS g LEFT JOIN {$config['tablepre']}bs_goods_view AS v ON g.`goods_id` = v.`goods_id` WHERE v.`year_month`>".intval(strtotime(trim($_GET['add_time_from'])));
            $sql.= " AND v.`year_month`<=".intval(strtotime(trim($_GET['add_time_to'])));
            $sql_end= " GROUP BY g.`goods_id`";
            $count_sql = "SELECT count(*) FROM ( ".$sql_start.$sql.$sql_end.") as t";
            $list_sql = $sql_start.$sql.$sql_end." LIMIT ".($curpage-1)*10 .",10";
            $totalNum = Model()->query($count_sql);
            $share_result = Model()->query($list_sql);

            pagecmd('setTotalNum', intval($totalNum[0]['count(*)']));
        }
        Tpl::output('share_list', $share_result);
        Tpl::output('show_page', Model()->showpage());
        Tpl::showpage('goods.shareRecord');
    }
}
